import App from './App'

import Vue from 'vue'
import Route from '@/utils/cloudObj.js';
Vue.prototype.$Route = Route;
import store from '@/utils/store.js';
Vue.prototype.$store = store;
import debounce from '@/utils/debounce.js';
import throttle from '@/utils/throttle.js';
Vue.prototype.$debounce = debounce;
Vue.prototype.$throttle = throttle;
import authManager from '@/utils/auth.js';
Vue.prototype.$auth = authManager;
import websocketManager from '@/utils/websocket.js';
Vue.prototype.$websocket = websocketManager;
import chatManager from '@/utils/chatManager.js';
Vue.prototype.$chat = chatManager;
import loginManager from '@/utils/loginManager.js';
Vue.prototype.$login = loginManager;

// 配置API基础URL
Vue.prototype.$config = {
	baseUrl: 'http://localhost:8080'
};

import routeGuard from '@/utils/routeGuard.js';
// 安装路由守卫
routeGuard.install();

// 封装通用错误处理函数
Vue.prototype.$parseError = function(err) {
	let errorMessage = err.message || ''; // 获取错误信息

	// 如果错误信息中包含冒号（即函数名），就去掉函数名部分
	if (errorMessage.includes(':')) {
		const parts = errorMessage.split(':');
		errorMessage = parts.slice(1).join(':').trim(); // 去掉函数名部分，只保留错误信息
	}

	// 判断是否是自定义的错误格式，例如 Error('参数不能为空')
	if (err instanceof Error && !errorMessage.match(/\d+:\S+/)) {
		// 如果没有错误代码，则默认返回一个错误提示
		return {
			code: null, // 没有错误代码
			msg: errorMessage || '未知错误'
		};
	}

	// 否则，按正常格式处理，匹配类似 401: 用户未登录
	let match = errorMessage.match(/(\d+):(.+)$/);
	if (match) {
		return {
			code: parseInt(match[1], 10), // 错误代码
			msg: match[2].trim() // 错误信息
		};
	}

	// 如果没有匹配到错误代码，返回默认错误信息
	return {
		code: null,
		msg: errorMessage || '未知错误'
	};
}

// 封装复制函数
Vue.prototype.$copy = function(text) {
	return uni.setClipboardData({
		data: text,
		success: () => {
			this.$Toast('复制成功');
		}
	});
}

// 封装预览图片
Vue.prototype.$previewImage = function(urls = [], index = 0) {
	// 如果不是数组，转成数组
	if (!Array.isArray(urls)) {
		urls = [urls];
	}
	if (urls[0]?.src) {
		urls = urls.map(item => item.src);
	}
	if (urls[0]?.url) {
		urls = urls.map(item => item.url);
	}
	return uni.previewImage({
		urls: urls,
		current: index
	})
}

// 封装时间戳转换为日期格式，xxx年xx月xx日
Vue.prototype.$formatDate = function(time) {
	const date = new Date(time);
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	return `${year}.${month}.${day}`;
};

// 封装时间戳转换为日期格式，xx月xx日
Vue.prototype.$formatDate2 = function(time) {
	const date = new Date(time);
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	return `${month}月${day}日`;
};

// 封装时间戳转换为日期格式，xx月xx日 xx:xx
Vue.prototype.$formatDate3 = function(time) {
	const date = new Date(time);
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	const hour = String(date.getHours()).padStart(2, '0');
	const minute = String(date.getMinutes()).padStart(2, '0');
	return `${month}月${day}日 ${hour}:${minute}`;
}

// 封装时间戳转换为日期时间格式，xxx年xx月xx日 xx:xx
Vue.prototype.$formatDateTime = function(time) {
	const date = new Date(time);
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	return `${year}年${month}月${day}日 ${hour}:${minute}`;
}

// 封装时间戳转换为x秒前x分钟前x小时前x天前x月前x年前
Vue.prototype.$timeFormat = function(time) {
	const now = new Date();
	const diff = now - new Date(time);
	const seconds = Math.floor(diff / 1000);
	const minutes = Math.floor(diff / 60000);
	const hours = Math.floor(diff / 3600000);
	const days = Math.floor(diff / 86400000);
	const months = Math.floor(diff / 2592000000);
	const years = Math.floor(diff / 31536000000);
	if (years > 0) {
		return years + '年前';
	} else if (months > 0) {
		return months + '月前';
	} else if (days > 0) {
		return days + '天前';
	} else if (hours > 0) {
		return hours + '小时前';
	} else if (minutes > 0) {
		return minutes + '分钟前';
	} else {
		return seconds + '秒前';
	}
}

// 封装提示弹窗
Vue.prototype.$Toast = async function(title, icon, duration, mask) {
	return uni.showToast({
		title: title,
		icon: icon || 'none',
		duration: duration || 1600,
		mask: mask || false
	})
}

Vue.prototype.$Loading = async function(title) {
	return uni.showLoading({
		title: title || '加载中',
		mask: true
	})
}

// 封装跳转
Vue.prototype.$ReLaunch = async function(path) {
	// 震动
	return uni.reLaunch({
		url: path
	})
}

Vue.prototype.$NavigateTo = async function(path) {
	// 震动
	return uni.navigateTo({
		url: path
	})
}

Vue.prototype.$SwitchTab = async function(path) {
	return uni.switchTab({
		url: path
	})
}

Vue.prototype.$NavigateBack = async function(path) {
	return uni.navigateBack({
		url: path
	})
}

Vue.prototype.$GoBack = async function(path) {
	// 震动
	uni.vibrateShort();
	const pages = getCurrentPages()
	if (pages && pages.length > 0) {
		const firstPage = pages[0]
		if (pages.length == 1 && (!firstPage.route || firstPage.route != 'pages/index/index')) {
			return uni.reLaunch({
				url: '/pages/index/index'
			})
		} else {
			return uni.navigateBack({
				delta: 1
			})
		}
	} else {
		return uni.reLaunch({
			url: '/pages/index/index'
		})
	}
}

Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
    store,
	...App
})
app.$mount()